{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "initial_id",
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    ""
   ]
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 1、关于对话模型中消息（message）的使用\n",
    "\n",
    "标准的对话模型的调用过程：\n",
    "\n",
    "invoke()的输入可以是多种类型，典型的类型有：① 字符串类型 ② 消息列表\n",
    "\n",
    "invoke()的输出类型：BaseMessage的子类：AIMessage"
   ],
   "id": "bd49c9a8b26464b2"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T02:10:00.198157Z",
     "start_time": "2025-08-23T02:09:51.996805Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_openai import ChatOpenAI\n",
    "import os\n",
    "import dotenv\n",
    "\n",
    "# 前提：加载配置文件\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "os.environ[\"OPENAI_BASE_URL\"] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "# 1、获取对话模型\n",
    "chat_model = ChatOpenAI(\n",
    "    # api_key=,\n",
    "    # base_url=,\n",
    "    model_name=\"gpt-4o-mini\",\n",
    ")\n",
    "\n",
    "# 2、调用对话模型\n",
    "response = chat_model.invoke(\"帮我解释一下什么是langchain?\")\n",
    "\n",
    "# 3、处理响应数据\n",
    "# print(response)\n",
    "print(response.content)\n",
    "print(type(response))  #<class 'langchain_core.messages.ai.AIMessage'>"
   ],
   "id": "cd67cf80cf802e39",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "LangChain 是一个用于构建基于大规模语言模型（如 OpenAI 的 GPT 系列）应用程序的框架。它旨在简化与语言模型进行交互的过程，并提供了一组工具和组件，帮助开发者构建更复杂的应用程序。\n",
      "\n",
      "LangChain 的核心特点包括：\n",
      "\n",
      "1. **模块化设计**：LangChain 提供了多个模块，允许开发者根据需求组合不同的功能。例如，可以处理输入输出、管理上下文、调用外部 API 以及更多。\n",
      "\n",
      "2. **支持多种数据源**：LangChain 可以与不同类型的数据源进行集成，比如数据库、文档存储和 API，帮助实现更灵活的数据处理。\n",
      "\n",
      "3. **内置的记忆功能**：LangChain 支持将对话的上下文和历史记忆存储起来，使得模型能在长时间对话中保持一致性和连贯性。\n",
      "\n",
      "4. **提示工程（Prompt Engineering）**：LangChain 提供了工具来设计和优化与语言模型的提示，提高生成结果的质量和相关性。\n",
      "\n",
      "5. **链式调用**：开发者可以将多个处理步骤串联起来，从而创建复杂的工作流，例如先处理用户输入，再通过外部 API 获取数据，然后生成响应。\n",
      "\n",
      "LangChain 适用于各种应用场景，如聊天机器人、自动化问答系统、内容生成、代码补全等，帮助开发者更轻松地利用语言模型的强大能力。\n",
      "<class 'langchain_core.messages.ai.AIMessage'>\n"
     ]
    }
   ],
   "execution_count": 2
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "关于消息：\n",
    "\n",
    "有典型的三类消息：SystemMessage \\ HumanMessage \\ AIMessage\n",
    "\n",
    "举例1：\n"
   ],
   "id": "52e5556e285b743c"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T02:15:43.901402Z",
     "start_time": "2025-08-23T02:15:43.891917Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.messages import SystemMessage, HumanMessage\n",
    "\n",
    "system_message = SystemMessage(content=\"你是一个英语教学方向的专家\")\n",
    "human_message = HumanMessage(content=\"帮我制定一个英语六级学习的计划\")\n",
    "\n",
    "messages = [system_message, human_message]\n",
    "\n",
    "print(messages)"
   ],
   "id": "a3b7df73e6bcb3cb",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[SystemMessage(content='你是一个英语教学方向的专家', additional_kwargs={}, response_metadata={}), HumanMessage(content='帮我制定一个英语六级学习的计划', additional_kwargs={}, response_metadata={})]\n"
     ]
    }
   ],
   "execution_count": 3
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "使用大模型，调用消息列表",
   "id": "85d8243d1bd0e326"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T02:17:34.328627Z",
     "start_time": "2025-08-23T02:17:25.342Z"
    }
   },
   "cell_type": "code",
   "source": [
    "response = chat_model.invoke(messages)\n",
    "print(type(response))\n",
    "print(response.content)"
   ],
   "id": "fbf1fb8097053003",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'langchain_core.messages.ai.AIMessage'>\n",
      "以下是一个为期三个月的英语六级学习计划，适合有一定基础的学生。该计划涵盖听力、阅读、写作和翻译等各个方面，建议每天坚持学习，灵活调整进度。\n",
      "\n",
      "### 第一个月：基础强化\n",
      "\n",
      "#### Week 1-2: 听力与词汇\n",
      "- **听力**: \n",
      "  - 每天听30分钟英语六级真题听力，集中在听辨和笔记。\n",
      "  - 选择适合的听力材料（如VOA、BBC）进行跟读练习。\n",
      "- **词汇**: \n",
      "  - 每天学习20个六级核心词汇，利用记忆法（如联想记忆）加深印象。\n",
      "  - 每周复习一遍所有词汇。\n",
      "\n",
      "#### Week 3-4: 阅读与语法\n",
      "- **阅读**:\n",
      "  - 每天阅读1篇六级真题阅读理解，分析文章结构和主要观点。\n",
      "  - 进行细节题、推理题的练习，培养答题技巧。\n",
      "- **语法**:\n",
      "  - 每周学习2-3个语法点，结合练习册进行练习。\n",
      "  - 进行重点句型的写作练习，注意语法的使用。\n",
      "\n",
      "### 第二个月：技能提升\n",
      "\n",
      "#### Week 5-6: 写作与翻译\n",
      "- **写作**:\n",
      "  - 学习六级作文的常用结构（如总分总），每周写2篇作文。\n",
      "  - 阅读优秀范文，分析其结构和用词。\n",
      "- **翻译**:\n",
      "  - 每周进行英语翻译练习，包括段落和句子。\n",
      "  - 学习常用句型和翻译技巧（如直译与意译）。\n",
      "\n",
      "#### Week 7-8: 模拟测试\n",
      "- **综合练习**:\n",
      "  - 每周进行一次全真模拟测试，时间和环境尽量接近正式考试。\n",
      "  - 分析测试结果，找出薄弱环节，并针对性练习。\n",
      "\n",
      "### 第三个月：实战演练\n",
      "\n",
      "#### Week 9-10: 深度复习\n",
      "- **查缺补漏**:\n",
      "  - 针对前两个月测试中发现的薄弱环节进行集中复习。\n",
      "  - 加强记忆和应用核心词汇和语法点，根据学习需要调整内容。\n",
      "\n",
      "#### Week 11-12: 考前冲刺\n",
      "- **模拟考试**:\n",
      "  - 每周进行1-2次全真模拟考试，时间控制在正式考试的时间内。\n",
      "  - 进行考后复盘，分析错题，注意总结经验教训。\n",
      "  \n",
      "- **心态调整**:\n",
      "  - 保持良好的作息，合理安排学习和休息时间，避免临考前的焦虑。\n",
      "  - 进行一些放松活动，提高心理素质。\n",
      "\n",
      "### 其他建议\n",
      "1. **学习资料**: 可以选择使用六级专用教材、网课及APP（如扇贝单词、知米背单词等）。\n",
      "2. **学习小组**: 如果条件允许，可以寻找学习伙伴，相互督促和帮助。\n",
      "3. **周末复习**: 每周末留出时间进行总结和复习。\n",
      "\n",
      "通过这个计划，希望能帮助你在英语六级考试中取得好成绩！坚持努力，多加练习！\n"
     ]
    }
   ],
   "execution_count": 4
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：",
   "id": "47199e4400132a3c"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T02:18:53.603499Z",
     "start_time": "2025-08-23T02:18:53.588398Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.messages import SystemMessage, HumanMessage\n",
    "\n",
    "system_message = SystemMessage(\n",
    "    content=\"你是一个英语教学方向的专家\",\n",
    "    additional_kwargs={\"tool\":\"invoke_func1\"}\n",
    ")\n",
    "human_message = HumanMessage(content=\"帮我制定一个英语六级学习的计划\")\n",
    "\n",
    "messages = [system_message, human_message]\n",
    "\n",
    "print(messages)"
   ],
   "id": "af9628c132bdc1de",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[SystemMessage(content='你是一个英语教学方向的专家', additional_kwargs={'tool': 'invoke_func1'}, response_metadata={}), HumanMessage(content='帮我制定一个英语六级学习的计划', additional_kwargs={}, response_metadata={})]\n"
     ]
    }
   ],
   "execution_count": 6
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例3:ChatMessage平时我们使用的不多，了解一下即可",
   "id": "a7bb4086b4472cd5"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T02:20:20.536694Z",
     "start_time": "2025-08-23T02:20:20.524497Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.messages import (\n",
    "    AIMessage,\n",
    "    HumanMessage,\n",
    "    SystemMessage,\n",
    "    ChatMessage\n",
    ")\n",
    "\n",
    "# 创建不同类型的消息\n",
    "system_message = SystemMessage(content=\"你是一个专业的数据科学家\")\n",
    "human_message = HumanMessage(content=\"解释一下随机森林算法\")\n",
    "ai_message = AIMessage(content=\"随机森林是一种集成学习方法...\")\n",
    "custom_message = ChatMessage(role=\"analyst\", content=\"补充一点关于超参数调优的信息\")\n",
    "\n",
    "print(system_message.content)\n",
    "print(human_message.content)\n",
    "print(ai_message.content)\n",
    "print(custom_message.content)"
   ],
   "id": "506ce66dc7e0a870",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "你是一个专业的数据科学家\n",
      "解释一下随机森林算法\n",
      "随机森林是一种集成学习方法...\n",
      "补充一点关于超参数调优的信息\n"
     ]
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 2、关于多轮对话与上下文记忆\n",
    "\n",
    "前提："
   ],
   "id": "8ef5f0c6e024b539"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T02:44:47.948683Z",
     "start_time": "2025-08-23T02:44:47.904297Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import os\n",
    "import dotenv\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "chat_model = ChatOpenAI(\n",
    "\tmodel=\"gpt-4o-mini\"\n",
    ")"
   ],
   "id": "c7232d20886db056",
   "outputs": [],
   "execution_count": 8
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "测试1：大模型本身是没有上下文记忆能力的\n",
    "\n"
   ],
   "id": "32caba81f5e4f26a"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T02:45:37.452512Z",
     "start_time": "2025-08-23T02:45:34.770207Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.messages import SystemMessage, HumanMessage\n",
    "\n",
    "sys_message = SystemMessage(\n",
    "    content=\"我是一个人工智能的助手，我的名字叫小智\",\n",
    ")\n",
    "human_message = HumanMessage(content=\"猫王是一只猫吗？\")\n",
    "\n",
    "messages = [sys_message, human_message]\n",
    "\n",
    "#调用大模型，传入messages\n",
    "response = chat_model.invoke(messages)\n",
    "# print(response.content)\n",
    "\n",
    "\n",
    "response1 = chat_model.invoke(\"你叫什么名字？\")\n",
    "print(response1.content)"
   ],
   "id": "d4df75b874a1c267",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我是一个人工智能助手，没有具体的名字，但你可以叫我“助手”或“AI”。有什么我可以帮助你的吗？\n"
     ]
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "测试2：",
   "id": "3064aed9eeb6de39"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T02:46:48.112770Z",
     "start_time": "2025-08-23T02:46:46.916202Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.messages import SystemMessage, HumanMessage\n",
    "\n",
    "sys_message = SystemMessage(\n",
    "    content=\"我是一个人工智能的助手，我的名字叫小智\",\n",
    ")\n",
    "human_message = HumanMessage(content=\"猫王是一只猫吗？\")\n",
    "human_message1 = HumanMessage(content=\"你叫什么名字？\")\n",
    "\n",
    "messages = [sys_message, human_message,human_message1]\n",
    "\n",
    "#调用大模型，传入messages\n",
    "response = chat_model.invoke(messages)\n",
    "print(response.content)\n"
   ],
   "id": "ddb5017992a3bd9a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我叫小智。请问有什么可以帮助你的？\n"
     ]
    }
   ],
   "execution_count": 10
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "测试3：",
   "id": "bcf09de2bfc5f52a"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T02:48:03.507508Z",
     "start_time": "2025-08-23T02:48:02.080818Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.messages import SystemMessage, HumanMessage\n",
    "\n",
    "sys_message = SystemMessage(\n",
    "    content=\"我是一个人工智能的助手，我的名字叫小智\",\n",
    ")\n",
    "human_message = HumanMessage(content=\"猫王是一只猫吗？\")\n",
    "\n",
    "sys_message1 = SystemMessage(\n",
    "    content=\"我可以做很多事情，有需要就找我吧\",\n",
    ")\n",
    "\n",
    "human_message1 = HumanMessage(content=\"你叫什么名字？\")\n",
    "\n",
    "messages = [sys_message, human_message,sys_message1,human_message1]\n",
    "\n",
    "#调用大模型，传入messages\n",
    "response = chat_model.invoke(messages)\n",
    "print(response.content)\n"
   ],
   "id": "ce9c5f8b2ce1fc4a",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我叫小智，您可以叫我助手。有需要帮助的地方吗？\n"
     ]
    }
   ],
   "execution_count": 11
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "测试4：",
   "id": "69dfffb17b66d2ec"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T02:48:47.675954Z",
     "start_time": "2025-08-23T02:48:45.268710Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.messages import SystemMessage, HumanMessage\n",
    "\n",
    "# 第1组\n",
    "sys_message = SystemMessage(\n",
    "    content=\"我是一个人工智能的助手，我的名字叫小智\",\n",
    ")\n",
    "human_message = HumanMessage(content=\"猫王是一只猫吗？\")\n",
    "\n",
    "messages = [sys_message, human_message]\n",
    "\n",
    "# 第2组\n",
    "sys_message1 = SystemMessage(\n",
    "    content=\"我可以做很多事情，有需要就找我吧\",\n",
    ")\n",
    "\n",
    "human_message1 = HumanMessage(content=\"你叫什么名字？\")\n",
    "\n",
    "messages1 = [sys_message1,human_message1]\n",
    "\n",
    "#调用大模型，传入messages\n",
    "response = chat_model.invoke(messages)\n",
    "# print(response.content)\n",
    "\n",
    "response = chat_model.invoke(messages1)\n",
    "print(response.content)"
   ],
   "id": "6798bfdc63cded86",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "我是一个人工智能助手，没有具体的名字，你可以叫我助手或者AI。如果你有任何问题，随时问我！\n"
     ]
    }
   ],
   "execution_count": 12
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "测试5：",
   "id": "bf3332df3f3b3ff2"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T02:49:44.772013Z",
     "start_time": "2025-08-23T02:49:43.519864Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_core.messages import SystemMessage, HumanMessage, AIMessage\n",
    "\n",
    "messages = [\n",
    "    SystemMessage(content=\"我是一个人工智能助手，我的名字叫小智\"),\n",
    "    HumanMessage(content=\"人工智能英文怎么说？\"),\n",
    "    AIMessage(content=\"AI\"),\n",
    "    HumanMessage(content=\"你叫什么名字\"),\n",
    "]\n",
    "\n",
    "messages1 = [\n",
    "    SystemMessage(content=\"我是一个人工智能助手，我的名字叫小智\"),\n",
    "    HumanMessage(content=\"很高兴认识你\"),\n",
    "    AIMessage(content=\"我也很高兴认识你\"),\n",
    "    HumanMessage(content=\"你叫什么名字\"),\n",
    "]\n",
    "\n",
    "messages2 = [\n",
    "    SystemMessage(content=\"我是一个人工智能助手，我的名字叫小智\"),\n",
    "    HumanMessage(content=\"人工智能英文怎么说？\"),\n",
    "    AIMessage(content=\"AI\"),\n",
    "    HumanMessage(content=\"你叫什么名字\"),\n",
    "]\n",
    "\n",
    "chat_model.invoke(messages2)"
   ],
   "id": "78ba75bfa7ce35f8",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "AIMessage(content='我叫小智。有什么我可以帮助你的吗？', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 13, 'prompt_tokens': 40, 'total_tokens': 53, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_efad92c60b', 'id': 'chatcmpl-C7Yc4CexF0a9rwfGrTHmp1OVT9xI3', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--d70d45e2-1c6f-4bb3-bedd-d3efba980561-0', usage_metadata={'input_tokens': 40, 'output_tokens': 13, 'total_tokens': 53, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})"
      ]
     },
     "execution_count": 13,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 13
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 3、关于模型调用的方法的说明\n",
    "\n",
    "invoke() / stream()\n",
    "\n",
    "batch():批量的调用\n",
    "\n",
    "ainvoke() / astream() / abatch():异步方法的调用\n",
    "\n",
    "举例1：体会invoke()阻塞式的调用"
   ],
   "id": "9a1ef3122e71f6f9"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T03:28:54.219622Z",
     "start_time": "2025-08-23T03:28:52.757811Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import os\n",
    "import dotenv\n",
    "from langchain_core.messages import HumanMessage\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "#初始化大模型\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "# 创建消息\n",
    "messages = [HumanMessage(content=\"你好，请介绍一下自己\")]\n",
    "\n",
    "# 非流式调用LLM获取响应\n",
    "response = chat_model.invoke(messages)\n",
    "\n",
    "# 打印响应内容\n",
    "print(response)"
   ],
   "id": "c54fe05615e41183",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "content='你好！我是一个人工智能助手，旨在提供信息和解答问题。我可以帮助你获取知识、解决疑问、提供建议等。如果你有任何问题或者需要讨论的主题，随时告诉我！' additional_kwargs={'refusal': None} response_metadata={'token_usage': {'completion_tokens': 47, 'prompt_tokens': 12, 'total_tokens': 59, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_efad92c60b', 'id': 'chatcmpl-C7ZDy9mkaVOH2rMyT0JLgum8ZPlQl', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None} id='run--d31ca017-0571-4506-8fc1-3a3eb762b4ce-0' usage_metadata={'input_tokens': 12, 'output_tokens': 47, 'total_tokens': 59, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}}\n"
     ]
    }
   ],
   "execution_count": 14
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例2：流式的演示",
   "id": "52dc83d52fe22d11"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T03:32:29.454849Z",
     "start_time": "2025-08-23T03:32:27.188786Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import os\n",
    "import dotenv\n",
    "from langchain_core.messages import HumanMessage\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"OPENAI_API_KEY\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "# 初始化大模型\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\",\n",
    "                        streaming=True  # 启用流式输出\n",
    "                        )\n",
    "\n",
    "# 创建消息\n",
    "messages = [HumanMessage(content=\"你好，请介绍一下自己\")]\n",
    "\n",
    "# 流式调用LLM获取响应\n",
    "print(\"开始流式输出：\")\n",
    "for chunk in chat_model.stream(messages):\n",
    "    # 逐个打印内容块\n",
    "    print(chunk.content, end=\"\", flush=True) # 刷新缓冲区 (无换行符，缓冲区未刷新，内容可能不会立即显示)\n",
    "\n",
    "print(\"\\n流式输出结束\")"
   ],
   "id": "ec28fa27d202a149",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "开始流式输出：\n",
      "你好！我是一个由OpenAI开发的人工智能助手，旨在回答问题、提供信息和协助解决各种问题。我的知识覆盖了许多领域，包括科学、技术、文化、历史等。如果你有任何具体的问题或需要帮助的地方，随时问我！\n",
      "流式输出结束\n"
     ]
    }
   ],
   "execution_count": 15
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "举例3：使用batch，测试批量调用",
   "id": "a4132cbc41dc9f1"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T06:26:14.261178Z",
     "start_time": "2025-08-23T06:26:07.926655Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import os\n",
    "import dotenv\n",
    "from langchain_core.messages import HumanMessage, SystemMessage\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ['OPENAI_API_KEY'] = os.getenv(\"OPENAI_API_KEY1\")\n",
    "os.environ['OPENAI_BASE_URL'] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "\n",
    "# 初始化大模型\n",
    "chat_model = ChatOpenAI(model=\"gpt-4o-mini\")\n",
    "\n",
    "messages1 = [SystemMessage(content=\"你是一位乐于助人的智能小助手\"),\n",
    "             HumanMessage(content=\"请帮我介绍一下什么是机器学习\"), ]\n",
    "\n",
    "messages2 = [SystemMessage(content=\"你是一位乐于助人的智能小助手\"),\n",
    "             HumanMessage(content=\"请帮我介绍一下什么是AIGC\"), ]\n",
    "\n",
    "messages3 = [SystemMessage(content=\"你是一位乐于助人的智能小助手\"),\n",
    "             HumanMessage(content=\"请帮我介绍一下什么是大模型技术\"), ]\n",
    "\n",
    "messages = [messages1, messages2, messages3]\n",
    "\n",
    "# 调用batch\n",
    "response = chat_model.batch(messages)\n",
    "\n",
    "print(response)\n"
   ],
   "id": "f53dcdd20d38a9f",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[AIMessage(content='机器学习是一种人工智能的子领域，旨在通过分析数据并从中学习，来使计算机系统能够自动改善其性能和预测能力，而无需被明确编程。简单来说，机器学习使计算机能够从经验中学习，并根据这些经验做出决策或预测。\\n\\n机器学习主要可以分为以下几种类型：\\n\\n1. **监督学习（Supervised Learning）**：在这种学习方式中，模型使用带标签的数据进行训练。每个输入数据都有一个相应的输出标签，机器学习算法通过学习输入和输出之间的关系来进行预测。应用实例包括分类（例如图片分类）和回归（例如房价预测）。\\n\\n2. **无监督学习（Unsupervised Learning）**：与监督学习不同，无监督学习使用的是没有标签的数据。模型通过发现数据中的模式和结构进行学习，常见的算法包括聚类（例如客户细分）和降维（例如主成分分析）。\\n\\n3. **半监督学习（Semi-Supervised Learning）**：这种方法结合了监督学习和无监督学习的元素，使用一小部分带标签的数据和大量未带标签的数据进行训练。这在获取带标签的数据成本较高的情况下特别有用。\\n\\n4. **增强学习（Reinforcement Learning）**：这种学习方式使智能体通过与环境的交互不断尝试和学习，从中获得反馈（奖励或惩罚），以优化其决策策略。广泛应用于游戏、机器人控制和自动驾驶等领域。\\n\\n机器学习的应用非常广泛，涵盖自然语言处理、计算机视觉、推荐系统、医疗诊断、金融预测等多个领域。随着技术的发展，机器学习在各行各业的应用前景仍在不断扩大。', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 379, 'prompt_tokens': 30, 'total_tokens': 409, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_efad92c60b', 'id': 'chatcmpl-C7bzVNNGyUQR4WkSt5Khjiok14r30', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--b542c105-8280-4581-931e-c71c8fd432c8-0', usage_metadata={'input_tokens': 30, 'output_tokens': 379, 'total_tokens': 409, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}}), AIMessage(content='AIGC（Artificial Intelligence Generated Content）指的是由人工智能生成的内容。这种内容可以是文字、图像、音频、视频等多种形式。近年来，随着深度学习、自然语言处理和计算机视觉等技术的发展，AIGC得到了迅速发展和广泛应用。\\n\\nAIGC的主要特点包括：\\n\\n1. **自动化生成**：AIGC能够通过算法自动生成内容，减少人工创作的时间和成本。\\n   \\n2. **多样性与个性化**：人工智能可以根据用户的偏好和需求生成定制化的内容，提供更具个性化的体验。\\n\\n3. **实时更新**：AIGC可以快速响应和生成内容，非常适合需要实时更新的信息，如新闻报道、社交媒体内容等。\\n\\n4. **创意与灵感**：AI工具可以为创作者提供灵感和建议，帮助他们在创作过程中产生新的想法。\\n\\n常见的AIGC应用包括聊天机器人（如智能客服）、内容创作工具（如写作助手）、图像生成工具（如DALL-E、Midjourney）等。在许多领域，如营销、教育、娱乐等，AIGC的应用正在不断扩大。\\n\\n需要注意的是，由于AIGC生成的内容可能涉及版权、伦理和准确性等问题，因此在使用和发布这些内容时，必须谨慎对待。', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 305, 'prompt_tokens': 31, 'total_tokens': 336, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_efad92c60b', 'id': 'chatcmpl-C7bzVHzIT1ZjZ2c0v1ARI50tH3t7z', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--f45ed5ec-54ac-46fa-96f9-fa481338c9fc-0', usage_metadata={'input_tokens': 31, 'output_tokens': 305, 'total_tokens': 336, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}}), AIMessage(content='大模型技术是指在深度学习和人工智能领域中，使用大型神经网络模型来处理和生成数据。通常，这些模型具备数以亿计甚至数万亿个参数，能够识别复杂的模式和关系，从而实现更高水平的任务性能。\\n\\n### 大模型技术的特点：\\n\\n1. **规模庞大**：大模型通常拥有巨大的参数量，使其能够捕捉复杂的特征和数据分布。\\n\\n2. **预训练和微调**：大模型一般采用预训练的方式。在一个大规模数据集上进行预训练后，再在特定任务上进行微调，利用迁移学习的优势。\\n\\n3. **多任务学习**：大模型可以同时进行多种任务，比如文本生成、翻译、问答等，具有较强的泛化能力。\\n\\n4. **自注意力机制**：许多大模型（如Transformer）采用自注意力机制，使得模型在处理数据时能够关注不同部分的信息，增强了上下文理解能力。\\n\\n### 应用领域：\\n\\n- **自然语言处理（NLP）**：大模型在语言翻译、文本生成、情感分析等任务中表现优异，如GPT、BERT等。\\n- **计算机视觉**：在图像识别、生成和分割等任务中，使用大模型能促进更高的准确率。\\n- **语音识别和合成**：大模型可以提升语音到文本的准确性以及文本到语音的自然度。\\n\\n### 挑战和展望：\\n\\n1. **计算资源需求**：训练和部署这样大型的模型需要大量的计算资源和耗电，限制了它们的广泛应用。\\n\\n2. **可解释性问题**：虽然大模型在性能上表现优异，但其模型内部的决策过程往往难以解释。\\n\\n3. **伦理与安全**：大模型可能会被滥用，产生虚假信息或偏见，亟需建立相应的伦理规范。\\n\\n总的来说，大模型技术正在推动人工智能的进步，带来许多创新和便利，但也面临着诸多挑战，研究者们正在积极探索解决方案以实现其更为广泛和负责任的应用。', additional_kwargs={'refusal': None}, response_metadata={'token_usage': {'completion_tokens': 489, 'prompt_tokens': 31, 'total_tokens': 520, 'completion_tokens_details': {'accepted_prediction_tokens': 0, 'audio_tokens': 0, 'reasoning_tokens': 0, 'rejected_prediction_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': 0, 'cached_tokens': 0}}, 'model_name': 'gpt-4o-mini-2024-07-18', 'system_fingerprint': 'fp_efad92c60b', 'id': 'chatcmpl-C7bzVC9XJNpmJDgGqjAJaLQSeoqOL', 'service_tier': None, 'finish_reason': 'stop', 'logprobs': None}, id='run--5e9f81dc-9c53-4429-8673-ef7245abeb3d-0', usage_metadata={'input_tokens': 31, 'output_tokens': 489, 'total_tokens': 520, 'input_token_details': {'audio': 0, 'cache_read': 0}, 'output_token_details': {'audio': 0, 'reasoning': 0}})]\n"
     ]
    }
   ],
   "execution_count": 20
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "举例4：关于同步和异步方法的调用\n",
    "\n",
    "体会1："
   ],
   "id": "2c6040aef2b61bd8"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T03:52:26.994579Z",
     "start_time": "2025-08-23T03:52:16.943008Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import time\n",
    "\n",
    "def call_model():\n",
    "    # 模拟同步API调用\n",
    "    print(\"开始调用模型...\")\n",
    "    time.sleep(5)  # 模拟调用等待,单位：秒\n",
    "    print(\"模型调用完成。\")\n",
    "\n",
    "def perform_other_tasks():\n",
    "    # 模拟执行其他任务\n",
    "    for i in range(5):\n",
    "        print(f\"执行其他任务 {i + 1}\")\n",
    "        time.sleep(1)  # 单位：秒\n",
    "\n",
    "def main():\n",
    "    start_time = time.time()\n",
    "    call_model()\n",
    "    perform_other_tasks()\n",
    "    end_time = time.time()\n",
    "    total_time = end_time - start_time\n",
    "    return f\"总共耗时：{total_time}秒\"\n",
    "\n",
    "# 运行同步任务并打印完成时间\n",
    "main_time = main()\n",
    "print(main_time)"
   ],
   "id": "f964e08175fd8e17",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "开始调用模型...\n",
      "模型调用完成。\n",
      "执行其他任务 1\n",
      "执行其他任务 2\n",
      "执行其他任务 3\n",
      "执行其他任务 4\n",
      "执行其他任务 5\n",
      "总共耗时：10.033676385879517秒\n"
     ]
    }
   ],
   "execution_count": 18
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "体会2：",
   "id": "849911b241ddb07a"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-08-23T03:55:33.637480Z",
     "start_time": "2025-08-23T03:55:28.610119Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import asyncio\n",
    "import time\n",
    "\n",
    "async def async_call(llm):\n",
    "    await asyncio.sleep(5)  # 模拟异步操作\n",
    "    print(\"异步调用完成\")\n",
    "\n",
    "async def perform_other_tasks():\n",
    "    await asyncio.sleep(5)  # 模拟异步操作\n",
    "    print(\"其他任务完成\")\n",
    "\n",
    "async def run_async_tasks():\n",
    "    start_time = time.time()\n",
    "    await asyncio.gather(\n",
    "        async_call(None),  # 示例调用，使用None模拟LLM对象\n",
    "        perform_other_tasks()\n",
    "    )\n",
    "    end_time = time.time()\n",
    "    return f\"总共耗时：{end_time - start_time}秒\"\n",
    "\n",
    "# # 正确运行异步任务的方式\n",
    "# if __name__ == \"__main__\":\n",
    "#     # 使用 asyncio.run() 来启动异步程序\n",
    "#     result = asyncio.run(run_async_tasks())\n",
    "#     print(result)\n",
    "\n",
    "\n",
    "# 在 Jupyter 单元格中直接调用\n",
    "result = await run_async_tasks()\n",
    "print(result)"
   ],
   "id": "18e9e611f22af499",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "异步调用完成\n",
      "其他任务完成\n",
      "总共耗时：5.0116283893585205秒\n"
     ]
    }
   ],
   "execution_count": 19
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
